import PlaneCtrl from "./PlaneCtrl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameCtrl extends cc.Component {

    @property({ type: cc.Node })
    maskNode: cc.Node = null;

    @property({ type: cc.Node })
    planeNode: cc.Node = null;

    @property({ type: cc.Node })
    bulletRoot: cc.Node = null;

    @property({ type: cc.Prefab })
    bulletPrefab: cc.Prefab = null;

    public static instance: GameCtrl = null;

    // 游戏是否暂停
    public isPause: boolean = true;

    // 子弹节点池
    private bulletPool: cc.NodePool = null;

    // 初始创建子弹个数
    private initBulletNum: number = 10;


    onLoad(): void {
        if (GameCtrl.instance == null) {
            GameCtrl.instance = this;
        } else {
            GameCtrl.instance.destroy();
            return;
        }

        this.isPause = true;

        this.node.on(cc.Node.EventType.TOUCH_START, this.startGame, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.movePlane, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.pauseGame, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.pauseGame, this);

        this.prepareBullet();
    }

    start() {

    }

    startGame(): void {
        this.maskNode.stopAllActions();
        this.maskNode.runAction(cc.fadeOut(0.2));
        this.isPause = false;
    }

    movePlane(e: cc.Touch): void {
        let planeCtrl: PlaneCtrl = this.planeNode.getComponent('PlaneCtrl');
        planeCtrl.movePlane(e);
    }

    pauseGame(): void {
        this.maskNode.stopAllActions();
        this.maskNode.runAction(cc.fadeIn(0.5));
        this.isPause = true;
    }

    private prepareBullet(): void {
        this.bulletPool = new cc.NodePool('bullet_pool');
        for (let i = 0; i < this.initBulletNum; i++) {
            let bulletNode = cc.instantiate(this.bulletPrefab);
            this.bulletPool.put(bulletNode);
        }
    }

    allocBullet(): cc.Node {
        console.log('分配子弹')

        var b = this.bulletPool.get();
        if (b === null) {
            b = cc.instantiate(this.bulletPrefab);
        }

        this.bulletRoot.addChild(b);
        return b;
    }

    freeBullet(bulletNode: cc.Node): void {
        // console.log('子弹回收')
        this.bulletPool.put(bulletNode);
        bulletNode.removeFromParent();
        console.log('回收子弹。节点池 size: ' + this.bulletPool.size())
    }



}